/**
 * @(#) WelfareMediator.as
 *
 * @date		2009. 03. 19.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	제증명신청 - Mediator
 * 				제증명 발행을 조회하고 신청하는 Presentation Logic을 관리 
 */
package com.skt.common_hr.welfare.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.OverViewMediator;
	import com.skt.common_hr.welfare.WelfareFacade;
	import com.skt.common_hr.welfare.events.SelectedYearEvent;
	import com.skt.common_hr.welfare.events.WelfareViewEvent;
	import com.skt.common_hr.welfare.model.BankAccountProxy;
	import com.skt.common_hr.welfare.model.StatementUrlProxy;
	import com.skt.common_hr.welfare.model.WelfareCodesProxy;
	import com.skt.common_hr.welfare.model.WelfareDetailProxy;
	import com.skt.common_hr.welfare.model.WelfareListProxy;
	import com.skt.common_hr.welfare.model.WelfareYearProxy;
	import com.skt.common_hr.welfare.view.components.WelfareView;
	import com.skt.common_hr.welfare.view.components.popGuide;
	import com.skt.common_hr.welfare.view.components.popHistory;
	import com.wcl.utils.NumberUtil;
	
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import mx.collections.ArrayCollection;
	import mx.core.IFlexDisplayObject;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class WelfareMediator extends OverViewMediator
	{
		public static const NAME:String = "WelfareMediator"; 

		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function WelfareMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		override protected function initializeView():void
 		{
 			super.initializeView();
            preloadData();
            onSelectList();
 		}
 		
 		override protected function activatedView():void
 		{
 			super.activatedView();
 			setEventListeners();
 			view.vsMain.selectedIndex = 0;
 		}
 		
 		override protected function closedView():void
 		{
 			super.closedView();
 			removeEventListeners();
 		}
 		
 		private function setEventListeners():void
 		{
 			view.addEventListener(SelectedYearEvent.SELECTED_YEAR, onSelectedYear);
            view.addEventListener(WelfareViewEvent.SELECTED_DATA, onSelectedData);
            view.addEventListener(WelfareViewEvent.INSERT_DATA, onInsertData);
            view.addEventListener(WelfareViewEvent.UPDATE_DATA, onUpdateData);
            view.addEventListener(WelfareViewEvent.DELETE_DATA, onDeleteData);
            view.addEventListener(WelfareViewEvent.PRINT_DATA, onPrintData);
            view.addEventListener(WelfareView.OPEN_GUIDE, onClickGuide);
            
            // 발생내역보기
            view.addEventListener(WelfareView.OPEN_HISTORY, onClickHistory);
            view.addEventListener(popHistory.CancelInput, onCancelInput);
 		}
 		
 		private function removeEventListeners():void
 		{
 			view.removeEventListener(SelectedYearEvent.SELECTED_YEAR, onSelectedYear);
            view.removeEventListener(WelfareViewEvent.SELECTED_DATA, onSelectedData);
            view.removeEventListener(WelfareViewEvent.INSERT_DATA, onInsertData);
            view.removeEventListener(WelfareViewEvent.UPDATE_DATA, onUpdateData);
            view.removeEventListener(WelfareViewEvent.DELETE_DATA, onDeleteData);
            view.removeEventListener(WelfareViewEvent.PRINT_DATA, onPrintData);
            view.removeEventListener(WelfareView.OPEN_GUIDE, onClickGuide);

            view.removeEventListener(WelfareView.OPEN_HISTORY, onClickHistory);         
            view.removeEventListener(popHistory.CancelInput, onCancelInput);   
 		}
 		
 		/**
 		 * 
 		 **/
 		
 		private function onClickHistory(e:Event):void 
		{
 			var Popup:IFlexDisplayObject = PopUpManager.createPopUp(view, popHistory, true);
 			PopUpManager.centerPopUp(Popup);
 			Popup.y -= 80;
 			
 			var popMediator:PopWelfareHistoryMediator = facade.retrieveMediator(PopWelfareHistoryMediator.NAME) as PopWelfareHistoryMediator;
 			popMediator = new PopWelfareHistoryMediator(Popup);
 			facade.registerMediator(popMediator);
 			
 			popMediator.onList(view.cbYear.selectedLabel);
		}

 		//팝업 닫기
 		private function onCancelInput(event:Event):void
 		{
 			//facade.removeMediator(popAnnuitySubtractionMediator.NAME);
 			//PopUpManager.removePopUp(Popup);
 		}
 				 		
 		private function preloadData():void
		{
			var yearProxy:WelfareYearProxy = facade.retrieveProxy(WelfareYearProxy.NAME) as WelfareYearProxy;
			yearProxy.load(Variables.myPernr);
			
			var codeProxy:WelfareCodesProxy = facade.retrieveProxy(WelfareCodesProxy.NAME) as WelfareCodesProxy;
			codeProxy.load();
			codeProxy.tradeComboLoad();
			
			var bankProxy:BankAccountProxy = facade.retrieveProxy(BankAccountProxy.NAME) as BankAccountProxy;
			bankProxy.load(Variables.myPernr);
		}
 		
 		
 		/****
 		 * 가이드 창 ac data 가공
 		 * **/
 		private function setGuide(acSubject:ArrayCollection, acDetail:ArrayCollection):void
 		{
			var oSubjectItem:Object;
			var oDetailItem:Object;
			for(var i:int=0; i<acSubject.length; i++) {
				oSubjectItem = {};
				oSubjectItem = acSubject.getItemAt(i);
							
				for(var j:int=0; j<acDetail.length; j++) {
					oDetailItem = {};
					oDetailItem = acDetail.getItemAt(j);				
					// 코드가 같을경우 detail에 추가 이름 필드 부여
					if(oSubjectItem.CODE == oDetailItem.CAFGBN) {
						oDetailItem.oSubject = oSubjectItem.TEXT; 
					}
				}			
			} 			
			openGuide(acDetail);
 		} 		

 		private function openGuide(ac:ArrayCollection):void 
		{
 			var Popup:IFlexDisplayObject = PopUpManager.createPopUp(view, popGuide, true);
 			PopUpManager.centerPopUp(Popup);
 			Popup.y -= 80;
 			popGuide(Popup).welfareList = ac;
		}
		 		
 		/****
 		 * 리스트 데이터 조회
 		 * **/
 		private function loadListData(year:String):void
 		{
	 		var proxy:WelfareListProxy = facade.retrieveProxy(WelfareListProxy.NAME) as WelfareListProxy;
 			proxy.load(Variables.myPernr, year);
 		}
 		
 		private function onSelectedYear(event:SelectedYearEvent):void
 		{
 			loadListData(event.year);
 		}
 		
 		private function onSelectList():void{
	 		//var proxy:WelfareListProxy = facade.retrieveProxy(WelfareListProxy.NAME) as WelfareListProxy;
 			//proxy.load('', view.cbYear.selectedItem.data);
 		}
 		
 		/**
 		 * 조회화면으로 이동
 		 * **/
 		private function onSelectedData(event:WelfareViewEvent):void
 		{
 			commonFacade.setStatusMessage("");
 			view.vsMain.selectedIndex = 1;
 			
 			
 			var detailViewMediator:ReqWelfareViewMediator = facade.retrieveMediator(ReqWelfareViewMediator.NAME) as ReqWelfareViewMediator;
 			if(!detailViewMediator){
				detailViewMediator = new ReqWelfareViewMediator(view.reqWelfareView);
				detailViewMediator.Gkey = event.Gkey;
	 			facade.registerMediator(detailViewMediator);
 			}else{
 				detailViewMediator.Gkey = event.Gkey;
 				detailViewMediator.initView();
 			}
 			commonFacade.setStatusMessage("");
 		}
 		
 		/**
 		 * 신청화면으로 이동
 		 * **/
 		private function onInsertData(event:WelfareViewEvent):void
 		{
 			commonFacade.setStatusMessage("");
 			view.vsMain.selectedIndex = 2;
 			
 			var insertViewMediator:ReqWelfareMediator = facade.retrieveMediator(ReqWelfareMediator.NAME) as ReqWelfareMediator;
 			if(!insertViewMediator){
				insertViewMediator = new ReqWelfareMediator(view.reqWelfare);
				insertViewMediator.Gkey = null;
				insertViewMediator.restMoney = event.restMoney;
				
				insertViewMediator.cbYear = view.cbYear.selectedItem as String;
				
				// silver 첫로딩때 안나와서 추가함.
				insertViewMediator.cleanView();
				
	 			facade.registerMediator(insertViewMediator);
 			}else{
 				insertViewMediator.Gkey = null;
 				insertViewMediator.restMoney = event.restMoney;
 				insertViewMediator.cbYear = view.cbYear.selectedItem as String;
 				insertViewMediator.cleanView();
 			}
 		}
 		
 		/**
 		 * 변경 화면으로 이동
 		 * **/
 		private function onUpdateData(event:WelfareViewEvent):void
 		{
 			updateData(event.Gkey, event.restMoney);
 		}
 		
 		private function updateData(gkey:String, restMoney:Number):void{
 			commonFacade.setStatusMessage("");
 			view.vsMain.selectedIndex = 2;
 			
 			var modifyViewMediator:ReqWelfareMediator = facade.retrieveMediator(ReqWelfareMediator.NAME) as ReqWelfareMediator;
 			if(!modifyViewMediator){
				modifyViewMediator = new ReqWelfareMediator(view.reqWelfare);
 				modifyViewMediator.Gkey = gkey;
 				modifyViewMediator.restMoney = restMoney;
 				modifyViewMediator.cbYear = view.cbYear.selectedItem as String;
	 			facade.registerMediator(modifyViewMediator);
 			}else{
 				modifyViewMediator.Gkey = gkey;
 				modifyViewMediator.restMoney = restMoney;
 				modifyViewMediator.cbYear = view.cbYear.selectedItem as String;
 				modifyViewMediator.cleanView();
 			}
 			
 			// 수정요청.. (그룹웨어키가 없으면 함수속에서 실행되지 않음)
 			modifyViewMediator.updateDataSet();
 		}
 		
 		/**
 		 * 삭제
 		 * **/
 		private function onDeleteData(event:WelfareViewEvent):void
 		{
 			CommonAlert.showMsgYesNo(commonFacade.bundle, "ALERT_PROMPT_DELETE", null
 								    ,"ALERT_TITLE_DEFAULT", view, function():void{deleteYes(event.Gkey)}, null);
 		}
 		
 		private function deleteYes(gKey:String):void{
 			var welfareProxy:WelfareDetailProxy = facade.retrieveProxy(WelfareDetailProxy.NAME) as WelfareDetailProxy;
			welfareProxy.deleteData(Variables.myPernr, gKey);
 		}
 		
 		/**
 		 * 프린트
 		 * **/
 		private function onPrintData(event:WelfareViewEvent):void
 		{ 
 			var statementProxy:StatementUrlProxy = facade.retrieveProxy(StatementUrlProxy.NAME) as StatementUrlProxy;
			statementProxy.load(event.Gkey);
			/* 
 			var printProxy:WelfareDetailProxy = facade.retrieveProxy(WelfareDetailProxy.NAME) as WelfareDetailProxy;
			printProxy.printDetailData(Variables.myPernr, event.Gkey);
			printProxy.printMoney(Variables.myPernr, view.year);
			printProxy.printUserInfoMoney(Variables.myPernr);//개인정보
			 */
 		}
 		
 		
 		private function onClickGuide(e:Event):void
 		{
// 			var proxy:WelfareListProxy = facade.retrieveProxy(WelfareListProxy.NAME) as WelfareListProxy;
// 			var urlReq:URLRequest = new URLRequest(proxy.itemURL);
// 			navigateToURL(urlReq, "_blank");

 			var welfareProxy:WelfareDetailProxy = facade.retrieveProxy(WelfareDetailProxy.NAME) as WelfareDetailProxy;
			welfareProxy.guideSubject();
			
			welfareProxy.guideDetail();
						
 		}
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return basicInterestMessages.concat( [
					WelfareFacade.LOAD_GUIDE_COMPLETE,
					WelfareFacade.LOAD_WELFARE_COMPLETE,
					WelfareFacade.LOAD_WELFARE_YEAR_COMPLETE,
					WelfareFacade.LOAD_WELFARE_YEAR_FAILED,
					WelfareFacade.CLOSED_REQ_VIEW,
					WelfareFacade.CANCEL_WELFARE_VIEW,
					WelfareFacade.CANCEL_WELFARE,
					WelfareFacade.DELETE_WELFARE_COMPLETE,
					WelfareFacade.DELETE_WELFARE_FAILED,
					WelfareFacade.LOAD_PRINT_DETAIL_COMPLETE,
					WelfareFacade.LOAD_PRINT_MONEY_COMPLETE,
					WelfareFacade.LOAD_PRINT_USERINFO_COMPLETE,
					WelfareFacade.QUICK_MODIFY_VIEW,
					StatementUrlProxy.LOAD_STATEMENT_URL_COMPLTE,
					StatementUrlProxy.LOAD_STATEMENT_URL_FAILED
					]);
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			super.handleNotification(note);
			switch(note.getName()) 
			{
				case WelfareFacade.LOAD_GUIDE_COMPLETE:	
					var acSubject:ArrayCollection = (note.getBody() as WelfareDetailProxy).acGuideSubject;				
					var acDetail:ArrayCollection = (note.getBody() as WelfareDetailProxy).acGuideDetail;
					setGuide(acSubject, acDetail);
					break;
				case WelfareFacade.LOAD_WELFARE_COMPLETE:
					view.welfareList = (note.getBody() as WelfareListProxy).welfareList;
					commonFacade.setStatusMessage("STATUS_LOADED_LIST", [view.welfareList.length]);
					view.usedAmount =  (note.getBody() as WelfareListProxy).usedAmount;
					break;
				case WelfareFacade.LOAD_WELFARE_YEAR_COMPLETE:
					view.welfareYears = (note.getBody() as WelfareYearProxy).yearList;
					break;
				case WelfareFacade.CLOSED_REQ_VIEW:
					loadListData(view.cbYear.selectedItem as String);
					view.vsMain.selectedIndex = 0;
					break;
				case WelfareFacade.CANCEL_WELFARE_VIEW:
					view.vsMain.selectedIndex = 0;
					break;
				case WelfareFacade.CANCEL_WELFARE:
					view.vsMain.selectedIndex = 0;
					break;	
				case WelfareFacade.DELETE_WELFARE_COMPLETE:
					loadListData(view.cbYear.selectedItem as String);
					break;	
				case WelfareFacade.DELETE_WELFARE_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, (note.getBody() as WelfareDetailProxy).msgStr);
					break;	
				case WelfareFacade.LOAD_PRINT_DETAIL_COMPLETE:
					onPrintDetailLoad(note.getBody() as WelfareDetailProxy);
					break;
				case WelfareFacade.LOAD_PRINT_MONEY_COMPLETE:
					onPrintMoneyLoad(note.getBody() as WelfareDetailProxy);
					break;
				case WelfareFacade.LOAD_PRINT_USERINFO_COMPLETE:
					onPrintUserInfoLoad(note.getBody() as WelfareDetailProxy);
					break;
				case WelfareFacade.QUICK_MODIFY_VIEW:
					trace("quick gkey : " + view.dgMain.selectedItem.GWAREKEY);
					updateData(view.dgMain.selectedItem.GWAREKEY, view.usedAmount.REMBT);
					break;	
				// 전표출력..	
				case StatementUrlProxy.LOAD_STATEMENT_URL_COMPLTE:
					onNotePrint((note.getBody() as StatementUrlProxy).url);
					break;
				case StatementUrlProxy.LOAD_STATEMENT_URL_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "("+(note.getBody() as StatementUrlProxy).errCode+")"+ (note.getBody() as StatementUrlProxy).errText);
					break;
												
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
		
		// 전표출력
		private function onNotePrint(url:String):void
		{
			var req:URLRequest = new URLRequest("../top_S_benefit/"+url);
			navigateToURL(req);
		} 				
		
		/**
		 * Main Module에서 QueryClose 메세지가 왔을 때의 처리
		 *     - 사용자에게 확인하고 View에 종료처리 -> MainModule에 'CLOSE_MODULE' 전송
		 * @param
		 * @return void
		 */
		 /*
		private function onQueryCloseModule():void
		{
			AlertHelper.showMsgYesNo("Close?", "확인", view, onMsgQueryCloseY, onMsgQueryCloseN);
		}
		*/
		/**
		 * 프린트상세정보
		 * */
		private function onPrintDetailLoad(proxy:WelfareDetailProxy):void
		{
			view.printView.printList = proxy.printList;
			view.printView.bankInfoVo = proxy.printMaster;
			view.printView.totalMoney = NumberUtil.NumberFormat(proxy.totMoney);
		}
		
		/**
		 * 프린트금액정보
		 * */
		private function onPrintMoneyLoad(proxy:WelfareDetailProxy):void
		{
			view.printView.amountVo = proxy.printUsedAmount;
		}
		
		/**
		 * 프린트개인정보
		 * */
		private function onPrintUserInfoLoad(proxy:WelfareDetailProxy):void
		{
			//PopUpManager.addPopUp(view.printView, view);
 			//PopUpManager.centerPopUp(view.printView);
 			
			view.printView.userInfoVo = proxy.profile;
			view.printView.doPrint();
		}
 
 
 
 
 
 
 
 
 
 
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////




		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():WelfareView
        {
            return viewComponent as WelfareView;
        }
		
		
	}
}